package com.symaster.backups.frame.element.pagination;

import java.awt.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.symaster.backups.frame.element.pagination.util.Util.getLeftButton;
import static com.symaster.backups.frame.element.pagination.util.Util.getRightButton;


/**
 * @author yinmiao
 * @version 2024/1/21
 */
class PaginationLayout implements LayoutManager {

    @Override
    public void addLayoutComponent(String name, Component comp) {

    }

    @Override
    public void removeLayoutComponent(Component comp) {

    }

    @Override
    public Dimension preferredLayoutSize(Container parent) {
        if (parent instanceof Pagination) {
            Pagination pagination = (Pagination) parent;
            int buttonSize = pagination.buttonSize;

            synchronized (pagination.getTreeLock()) {
                Container parent1 = pagination.getParent();
                if (parent1 == null) {
                    return new Dimension(100, buttonSize);
                }

                return new Dimension(parent1.getWidth(), buttonSize);
            }
        } else {
            throw new IllegalArgumentException("parent instanceof Pagination");
        }
    }

    @Override
    public Dimension minimumLayoutSize(Container parent) {
        return preferredLayoutSize(parent);
    }

    @Override
    public void layoutContainer(Container parent) {
        if (parent instanceof Pagination) {
            Pagination pagination = (Pagination) parent;
            int buttonSize = pagination.buttonSize;

            synchronized (pagination.getTreeLock()) {
                Component[] components = pagination.getComponents();

                List<Button> collect = Arrays.stream(components)
                        .filter(e -> {
                            if (e instanceof Button) {
                                Button button = (Button) e;
                                return button.getButtonType() == ButtonType.INDEX_BUTTON || button.getButtonType() == ButtonType.MORE_BUTTON;
                            }
                            return false;
                        })
                        .map(e -> ((Button) e))
                        .sorted(Comparator.comparingInt(Button::getIndex))
                        .collect(Collectors.toList());

                getLeftButton(components).setBounds(0, 0, buttonSize, buttonSize);

                int xOffset = buttonSize;
                for (Button button : collect) {
                    button.setBounds(xOffset, 0, buttonSize, buttonSize);
                    xOffset += buttonSize;
                }

                getRightButton(components).setBounds(xOffset, 0, buttonSize, buttonSize);
            }
        }
    }


}
